import enctool
import ftplib
import paramiko
import sys

__handler = None


class SimpleFtp:
	def __init__(self, hostname, username, password):
		self.prefix = 'ftp://%s:%s@%s' % (username, password, hostname)
		# Not sure of exactly where to go from here until I confirm that
		# using a URL like this in a web browser or something can indeed
		# grab stuff off the server. I have a feeling I'll need to incorporate
		# the /home/js84540/ part of the URL, which is unfortunate.
	
def get_handler(configuration):
	global __handler
	if __handler is None:
		__handler = SshHandler(configuration)
	return __handler

class SshHandler:
	def __init__(self, configuration):
		self.configuration = configuration
		self.ssh = self.__setup_ssh_client()
		if self.ssh is None:
			self.sftp = None
		else:
			self.sftp = self.ssh.open_sftp()
		self.ftp = self.__setup_ftp_client()
		
	def __setup_ftp_client(self):
		if self.configuration is None:
			print 'enctool has not been configured yet.'
			return None
		conf = self.configuration
		client = ftplib.FTP(conf['hostname'], user=conf['username'], passwd=conf['password'])
		
	def __setup_ssh_client(self):
		if self.configuration is None:
			print 'enctool has not been configured yet.'
			return None
		conf = self.configuration
		client = paramiko.SSHClient()
		client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
		client.connect(conf['hostname'], port=conf['port'], username=conf['username'], password=conf['password'])
		return client
	
	def run_command(self, command, ignore_err=True):
		'''Method for running a command that requires no stdin input. Will return a string of the stdout output if ignore_err is False, and a two-tuple in the form of (stdin_output, stderr_output) if True'''
		stdin, stdout, stderr = self.ssh.exec_command(command)
		stdin.close()
		output = ''.join(stdout.readlines())
		error = ''.join(stderr.readlines())
		stdout.close()
		stderr.close()
		if ignore_err:
			return output
		else:
			return output, error
	
	def close(self):
		transport = self.sftp.get_channel().get_transport()
		self.ssh.close()
		self.sftp.close()
		transport.close()

def main():
	configuration = enctool.get_configuration()
	if configuration is None:
		print 'Configuration has not been setup. Use enctool to do this'
		sys.exit(1)
	handler = get_handler(configuration)
	output, error = handler.run_command('ls -l', ignore_err=False)
	print 'Standard out:', output
	print 'Standard err:', error
	print '------'
	files = handler.sftp.listdir()
	print 'Files:', files
	
	print 'Closing handler...'
	handler.close()
	print 'Handler closed.'
	print 'Done'

if __name__ == '__main__':
	main()
